package com.mmp.main.servlet.spinventory;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.mmp.common.bo.Message;
import com.mmp.common.servlet.BasicServlet;
import com.mmp.main.endpoints.SPInventoryNotificationsEndPoint;
import com.mmp.main.entity.Site;
import com.mmp.main.entity.SpInventoryContent;
import com.mmp.main.entity.SpInventoryTransaction;
import com.mmp.main.entity.User;
import com.mmp.main.util.WebUtil;

public class AddNewSPCategoryProcessServlet extends BasicServlet {

	@Autowired
	SPInventoryNotificationsEndPoint spCategoryNotifier;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {

		Integer quantity = WebUtil.getParamValueAsInteger(request, "quantity", 0);
		Float unitPrice = WebUtil.getParamValueAsFloat(request, "price", 0f);
		User currentUser = getSessionUser(request);
		Site currentSite = currentUser.getSite();
		Date now = new Date();

		SpInventoryContent spInventoryContent = new SpInventoryContent();
		spInventoryContent.setSite(currentSite);
		spInventoryContent.setCode(WebUtil.getParamValue(request, "code", null));
		spInventoryContent.setName(WebUtil.getParamValue(request, "name", null));
		spInventoryContent.setThreshold(WebUtil.getParamValueAsInteger(request, "threshold", 0));
		spInventoryContent.setAvailableQuantity(quantity);
		spInventoryContent.setAvgUnitPrice(unitPrice);
		spInventoryContent.setCreatedBy(currentUser);
		spInventoryContent.setCreatedIn(now);

		spInventoryContent = dbQueryManager.persistEntity(spInventoryContent);

		SpInventoryTransaction spInventoryTransaction = new SpInventoryTransaction();
		spInventoryTransaction.setSite(currentSite);
		spInventoryTransaction.setSpInventoryContent(spInventoryContent);
		spInventoryTransaction.setInput(true);
		spInventoryTransaction.setQuantity(quantity);
		spInventoryTransaction.setUnitPrice(unitPrice);
		spInventoryTransaction.setPerformedBy(currentUser);
		spInventoryTransaction.setPerformedIn(now);

		spInventoryTransaction = dbQueryManager.persistEntity(spInventoryTransaction);

		// Message msg = null;
		//
		// try {
		//
		// dbTransManager.save(spInventoryContent, spInventoryTransaction);
		// msg = new Message("تمت  إضافة الصنف بنجاح",
		// Message.MESSAGE_TYPE.SUCCESS);
		//
		// } catch (Exception e) {
		// msg = new Message("لم تتم العملية بنجاح نتيجة حدوث خطأ بالنظام",
		// Message.MESSAGE_TYPE.ERROR);
		// }

		spCategoryNotifier.broadcastNotificationUpdates(getSessionSiteId(request));

		setMessage(request, new Message("تمت  إضافة الصنف بنجاح", Message.MESSAGE_TYPE.SUCCESS));

		sendRedirect(request, response, "AddNewSPCategoryDisplay");

	}

}
